using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody playerRb;

    private float thrust = 200.0f;

    [SerializeField] private GameObject bulletPrefab;

    [SerializeField] private GameObject bulletAnchor;

    [SerializeField] private GameObject shield;

    private float shieldActivationTime = 5.0f;

    [SerializeField] private GameManager gameManager;

    private bool isShielded = false; // 控制护盾防护功能
    
    [SerializeField] private ParticleSystem engineTrail;
    
    private float boostSpeed = 300.0f;


    private void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        shield.SetActive(false);
        engineTrail.Stop();
    }

    private void Update()
    {
        if (gameManager.isGameActive && !gameManager.isPaused)
        {
            Vector3 mousePos =
                Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));
            transform.LookAt(mousePos, Vector3.back);
            // Quaternion rotation = Quaternion.LookRotation(mousePos, Vector3.back);
            // transform.rotation = rotation;

            float sideInput = Input.GetAxis("Horizontal");
            float forwardInput = Input.GetAxis("Vertical");

            playerRb.AddRelativeForce(Vector3.forward * forwardInput * thrust);
            playerRb.AddRelativeForce(Vector3.right * sideInput * thrust, ForceMode.Force);

            if (Input.GetMouseButtonDown(0))
            {
                Vector3 lookPos = mousePos - transform.position;
                Quaternion lookRotation = Quaternion.LookRotation(lookPos, Vector3.right);
                Instantiate(bulletPrefab, bulletAnchor.transform.position, lookRotation);
            }
            
            //boost speed
            if (Input.GetKeyDown(KeyCode.LeftShift))
            {
                playerRb.AddRelativeForce(Vector3.forward * boostSpeed, ForceMode.Impulse);
                engineTrail.Play();
            }
            if (Input.GetKeyUp(KeyCode.LeftShift))
                engineTrail.Stop();
            
            //handle particle trail on ship
            if (Input.GetKeyDown(KeyCode.W))
                engineTrail.Play();
            else if (Input.GetKeyUp(KeyCode.W))
                engineTrail.Stop();
        }
    }

    public void ShieldActivated()
    {
        // TODO: 完成Player的防护功能
        isShielded = true;
        shield.SetActive(true);
        StartCoroutine(ShieldTimerCoroutine());
    }

    private IEnumerator ShieldTimerCoroutine()
    {
        yield return new WaitForSeconds(shieldActivationTime);
        isShielded = false;
        shield.SetActive(false);
    }

    public void DamageDealt()
    {
        if (!isShielded)
            gameManager.RemoveLife(1);
    }
}